<template>
   <search-table
       :page-pos="pagePos"
     :data="partList"
     :columns="columns"
     :page.sync="queryParams.pageIndex"
     :size.sync="queryParams.pageSize"
     :total="partTotal"
     :loading="partListLoading"
     @queryFun="getNewData"
     >
     <template slot="search">
       <Upload action="a" class="my-upload" :before-upload="handlerComponent" v-if="isPublic === 'N'">
         <Button type="primary" ghost >组件分析</Button>
       </Upload>
       <Button type="primary" ghost class="md-add-jh" @click="showModal(null)">创建组件</Button>
       <Button type="primary" v-if="$route.query.productId && isPublic === 'N'" ghost class="md-add-jh" @click="relativeModule">关联组件</Button>
       <Divider type="vertical" style="margin: 10px 0px 10px 10px;" />
       <Select filterable clearable v-model="queryParams.type" @on-change="selectModule" placeholder="组件类型" style="margin-left: 15px;width: 150px">
         <Option v-for="item in moduleList" :key="item.value" :value="item.value">{{item.label}}</Option>
       </Select>
       <Input v-model.trim="queryParams.name"  clearable placeholder="组件名称" @on-change="searchPartName" style="width: 180px;margin-left: 15px" />
       <Button class="header-btn" type="primary" ghost style="height: 32px;margin-left: 5px;" @click="refreshPartList()">
         <i class="el-icon-refresh-right" />
       </Button>
     </template>
     <Modal
       v-model="detailModalData.show"
       title="组件详情"
       footer-hide
       class="my-modal">
       <div class="item-table">
         <p>
           <span class='label'>组件名称</span>

           <span>{{ detailInfo.name }}</span>
         </p>
         <p>
           <span class='label'>组件类型</span>
           <span>{{ typeOptions[detailInfo.type] && typeOptions[detailInfo.type].label }}</span>
         </p>
         <p>
           <span class='label'>物料清单引用标识</span>
           <span>{{ detailInfo.bomId }}</span>
         </p>
         <p>
           <span class='label'>版本号</span>
           <span>{{ detailInfo.version }}</span>
         </p>
         <p>
           <span class='label'>分组</span>
           <span>{{ detailInfo.groupId }}</span>
         </p>
         <p>
           <span class='label'>最新版本</span>
           <span>{{ detailInfo.latestVersion }}</span>
         </p>
         <p>
           <span class='label'>作者</span>
           <span>{{ detailInfo.author }}</span>
         </p>
         <p>
           <span class='label'>供应商</span>
           <span>{{ detailInfo.publisher }}</span>
         </p>
         <p>
           <span class='label'>包URL</span>
           <span>{{ detailInfo.groupAddress }}</span>
         </p>
         <p>
           <span class='label'>CPE名称</span>
           <span>{{ detailInfo.enumItem }}</span>
         </p>
         <p>
           <span class='label'>软件标识标签</span>
           <span>{{ detailInfo.swid }}</span>
         </p>
         <p>
           <span class='label'>对象标识</span>
           <span>{{ detailInfo.objectId }}</span>
         </p>
         <p>
           <span class='label'>文件名称</span>
           <span>{{ detailInfo.fileName }}</span>
         </p>
         <p>
           <span class='label'>描述</span>
           <span>{{ detailInfo.description }}</span>
         </p>
         <p>
           <span class='label'>许可类型</span>
           <span>{{ detailInfo.licenseType }}</span>
         </p>
         <p>
           <span class='label'>许可文件链接</span>
           <span>{{ detailInfo.licenseFileLink }}</span>
         </p>
         <p>
           <span class='label'>版权说明</span>
           <span>{{ detailInfo.licenseDescription }}</span>
         </p>
         <p>
           <span class='label'>MD5</span>
           <span>{{ detailInfo.md5 }}</span>
         </p>
         <p>
           <span class='label'>SHA1</span>
           <span>{{ detailInfo.sha1 }}</span>
         </p>
         <p>
           <span class='label'>SHA256</span>
           <span>{{ detailInfo.sha256 }}</span>
         </p>
         <p>
           <span class='label'>SHA512</span>
           <span>{{ detailInfo.sha512 }}</span>
         </p>
         <p>
           <span class='label'>SHA3 256</span>
           <span>{{ detailInfo.sha3256 }}</span>
         </p>
         <p>
           <span class='label'>SHA3 512</span>
           <span>{{ detailInfo.sha3512 }}</span>
         </p>
         <p>
           <span class='label'>注意事项</span>
           <span>{{ detailInfo.announcements }}</span>
         </p>
       </div>
     </Modal>
     <relevance-part-module
       :productId="productId"
       :type="1"
       hideButton
       :partId="$route.query.id"
       ref="relevancPartModule"
       @relevance-success="getNewData"></relevance-part-module>
     <products-group-modal
       ref="productsGroupModal"
       :productId="productId"
       :partId="$route.query.id"
       @add-succee="getNewData"
       @update-succee="getNewData"></products-group-modal>
     <drawers @on-close="getNewData" ref="drawerExternalLinks" title="外部参考链接" :width="1000">
       <external-links ref="externalLinks"></external-links>
     </drawers>
     <drawers @on-close="getNewData" ref="drawerPotential" title="关联威胁" :width="1200">
         <potential-vulnerability
           ref="potentialVulnerability"
           :productId="productId"
           :moduleId="currentModuleId"
           :partId="$route.query.id"></potential-vulnerability>
     </drawers>
   </search-table>
</template>

<script>
import {
  deleteProductComponent,
  queryProductComponentList
} from '../api/productComponent'
import {
  deleteRelationItem,
  importBom, queryProductPartList,
} from '../api/productPart'
import RelevancePartModule from '../../components/relevance-part-module'
import ProductsGroupModal from '../../components/products-group-modal'
import ExternalLinks from './external-links'
import PotentialVulnerability from './potential-vulnerability'
import {MODULE_TYPE_OPTIONS} from '../../paramsConfig'
import {productPartTypeEscape} from "../logic/assetLogic";
import urlList from "./urlList.vue";
import drawers from "../../components/drawers.vue";

export default {
    name: 'ModuleManage',
    components: {
      drawers, urlList,
        RelevancePartModule,
        ProductsGroupModal,
        ExternalLinks,
        PotentialVulnerability
    },
    props: {
        productId: {
            type: String,
            default: ''
        },
        isPublic: {
            type: String,
            default: 'N'
        },
      pagePos:{
        type:String,
        default: 'top'
      },
    },
    data() {
        return {
          moduleList:[],
          partList:[],
          partTotal:0,
          partListLoading:false,
          queryParams:{},
            drawerData: {
                externalLinks: false,
                potential: false
            },
            currentModuleId: '',
            optionList: [],
            typeOptions: MODULE_TYPE_OPTIONS.map((item, index) => {
                return {
                    value: index,
                    label: item
                }
            }).filter(item => [1, 2, 3, 4, 5].includes(item.value)),
            detailModalData: {
                show: false
            },
            detailInfo: {},
            columns: [
                {
                    title:'组件名称',
                    key:'name',
                },
                {
                    title:'版本',
                    key:'version'
                },
                {
                    title:'组件类型',
                    key:'type',
                    minWidth:120,
                    render:(h,params)=>{
                        let obj = productPartTypeEscape(params.row.type)
                        return h('Tag',{
                            props:{
                                color: obj.color
                            }
                        }, obj.text)
                    }
                },
                {
                    title:'分组',
                    key:'groupId'
                },
                {
                    title:'许可类型',
                    key:'licenseType',
                },
                {
                    title:'最大威胁',
                    key:'maxThreatValue'
                },
                {
                    title:'风险评分',
                    key:'lastInheritedRiskScore'
                },
                {
                    title: '操作',
                    slot: 'action',
                    width: 320,
                    opList: [
                        {
                            txt: '详情',
                            fun: (obj) => {
                                this.detailModalData.show = true
                                this.detailInfo = obj
                            }
                        },
                        {
                            txt: '修改',
                          fun:(obj)=>{
                                this.showModal(obj)
                            },
                        },
                        {
                            txt: '外部参考链接',
                            fun: (obj) => {
                                this.drawerData.externalLinks = true
                                this.$nextTick(() => {
                                  this.$refs.drawerExternalLinks.openDrawer()
                                    this.$refs.externalLinks.init(obj)
                                })
                            },
                        },
                        {
                            txt: '关联威胁',
                            fun:(obj)=>{
                                this.currentModuleId = obj.id
                                this.$nextTick(() => {
                                  
                                  this.$refs.drawerPotential.openDrawer()
                                    this.$refs.potentialVulnerability.init(obj)
                                })
                            }
                        },
                        {
                            txt: '删除',
                            tooltip: true,
                            type:'delete',
                            title: '确定要删除吗？',
                            fun: obj => this.deleteItem([obj.id])
                        },
                    ]
                }
            ],
            //搜索模块
            textFields: [
                {
                    label: '',
                    key: 'name',
                    type: 'text',
                    placeholder:'请输入组件名称',
                    slotName: null,
                    hasButton: false, // 在这个示例中，不需要在性别字段后面添加按钮
                    hasButton1:false
                },
                {
                    key: 'type',
                    label: '组件类型',
                    type: 'select',
                    options: MODULE_TYPE_OPTIONS.map((item, index) => {
                        return {
                            value: index,
                            label: item
                        }
                    }).filter(item => [1, 2, 3, 4, 5].includes(item.value)),
                    optionsLoaded: true, // 标记选项是否已加载
                },
            ],
            formData:{
                name:'',
                type: '',
                productId: this.productId,
                partId: this.$route.query.id
            },
            fieldChangeCallbacks:{
                name: this.getNewData,
                type: this.getNewData
            },
            formStyle:{
                direction:'horizon',
                left:true
            },
            textFields1: [
                {
                    label: '',
                    type: 'upload',
                    placeholder:'组件分析',
                    handleBeforeUpload: (file) => {
                        let strs = file.name.split('.')
                        let suffix = strs[strs.length - 1] || '';
                        if (!['xml'].includes(suffix)) {
                            this.$Message.warning('请上传xml格式文件');
                            return false
                        }
                        // if (file.size > 5242880) {
                        //     this.$Message.warning('文件大小不能超过5M');
                        //     return false
                        // }
                        importBom(this.$route.query.id, file).then(({ code, message }) => {
                            if (code !== 1) {
                            this.$Message.warning(message)
                            return
                            }
                            this.$Message.success('文件上传成功，等待解析后查询组件数据......')
                        })
                        return false
                    }
                },
                {
                    label: '',
                    key: 'type',
                    type: 'dropdown',
                    placeholder:'创建组件',
                    options:[
                        {
                            value:'create-part',
                            label:'创建组件'
                        },
                        {
                            value:'import-part',
                            label:'关联组件'
                        }
                    ],
                    slotName: null,
                    hasButton: false, // 在这个示例中，不需要在性别字段后面添加按钮
                    hasButton1:false
                }
            ],
            formData1:{
            },
            fieldChangeCallbacks1:{
                type:this.openAddModal,
            },
            formStyle1:{
                direction:'horizon',
                right:true
            },
        }
    },
    methods: {
      getNewData(isRefresh){
        // 列表
        if (!isRefresh) { // 非刷新操作才需要展示等待中的画面
          this.partListLoading = true
        }
        this.queryParams.productId = this.$route.query.productId;
        this.queryParams.partId = this.$route.query.id;
        queryProductComponentList(this.queryParams)
            .then(res => {
              if (res.code === 1) {
                this.partTotal =res.data.total;
                this.partList = res.data.items;
              }
              this.partListLoading = false
            })
            .catch(err => {
              this.partListLoading = false
            })
      },
      handlerComponent(file){
        let strs = file.name.split('.')
        let suffix = strs[strs.length - 1] || '';
        if (!['xml'].includes(suffix)) {
          this.$Message.warning('请上传xml格式文件');
          return false
        }
        // if (file.size > 5242880) {
        //   this.$Message.warning('文件大小不能超过5M');
        //   return false
        // }
        importBom(this.$route.query.id, file).then(({ code, message }) => {
          if (code !== 1) {
            this.$Message.warning(message)
            return
          }
          this.$Message.success('文件上传成功，等待解析后查询组件数据......')
        })
        return false
      },
      selectModule(){
        this.queryParams.pageIndex = 1;
        this.getNewData()
      },
      searchPartName(){
        this.queryParams.pageIndex = 1;
        this.getNewData()
      },
      refreshPartList(){
        this.queryParams = {
          pageIndex:1,
          pageSize:10
        }
        this.getNewData()
      },
      relativeModule(){
        this.$refs.relevancPartModule.showRelevanceModal()
      },
        // 删除组件
        deleteItem(ids) {
            if(!this.productId){
              deleteProductComponent(ids).then(res=>{
                if(res.code===1){
                  this.$Message.success(`删除成功`)
                  // 删除后展示当前页，当前页没有数据展示前一页
                  this.queryParams.pageIndex = (this.partList.length === 1 && this.queryParams.pageIndex > 1) ?
                    this.queryParams.pageIndex - 1 : this.queryParams.pageIndex;
                  this.getNewData()
                }else{
                  this.$Message.warning(res.message)
                }
              })
            }else{
              deleteRelationItem(this.$route.query.id, this.productId, ids).then(({ code, message }) => {
                if (code !== 1) {
                  this.$Message.warning(message)
                  return
                }
                this.$Message.success(`删除成功`)
                // 删除后展示当前页，当前页没有数据展示前一页
                this.queryParams.pageIndex = (this.partList.length === 1 && this.queryParams.pageIndex > 1) ?
                  this.queryParams.pageIndex - 1 : this.queryParams.pageIndex;
                this.getNewData()
              }).catch(() => {
                this.$Message.error(`删除异常`)
              })
            }

        },
        // 下载文件
        downloadFile(item) {
            if (!item.fileId) {
                return
            }
            let a = document.createElement('a');
            let fileName = item.fileName; //filename名称截取
            a.href = `/api/minio/download/${item.fileId}`;
            a.download = fileName; //命名下载名称
            a.click(); //点击触发下载
        },
        openAddModal(val) {
            if(val=='create-part'){
                this.showModal()
            }else{
                this.$refs.relevancPartModule.showRelevanceModal()
            }
        },
        // 打开关联组件的模态框，初始化数据
        getPartOptions() {
            Promise.all([queryProductComponentList({
                pageIndex: 1,
                pageSize: 2147483646,
                productId: this.productId
            }), queryProductComponentList({
                pageIndex: 1,
                pageSize: 2147483646,
            })]).then(res => {
                let selfIds = [], allOptionList = []
                res.forEach((item, index) => {
                    let { code, data } = item
                    if (index === 0) { // 本产品已有的组件
                        if (code === 1) {
                            selfIds = (data.items || []).map(item => item.id)
                        }
                    } else { // 其他组件
                        if (code === 1) {
                            allOptionList = data.items || []
                        }
                    }
                })
                this.optionList = allOptionList.filter(item => !selfIds.includes(item.id))
            })
        },
        // 打开模态框
        showModal(data) {
            this.$refs.productsGroupModal.showModal(data)
        },
    },
    mounted() {
      this.moduleList = MODULE_TYPE_OPTIONS.map((item,index)=>{
        return {
          label:item,
          value:index
        }
      })
      this.getNewData()
    }
}
</script>

<style scoped>
.module-manage {
    display: flex;
    flex-direction: column;
    height: 100%;
    gap:14px;

}
.module-manage .table-body{
  flex: 1;
  height: 0;
}
.my-form-item {
    position: relative;


}
.my-form-item  /deep/ .ivu-form-item-content {
  display: flex;
}
.my-form-item  /deep/ .ios-alert {
  color: orange;
  font-size: 16px;
  cursor: pointer;
}
.my-form-item {
    position: relative;
}
.my-form-item /deep/ .ivu-form-item-content {
    display: flex;
}
.my-form-item /deep/ .ivu-form-item-content .ivu-checkbox-wrapper {
    margin-left: 10px;
    width: 66px;
}
.item-table {
  display: table;
  width: 100%;
  border: 1px solid #eee;
  table-layout: fixed;
  word-break: break-all;
}
.item-table p {
  display: table-row;
  line-height: 36px;
  text-align: center;
}
.item-table p span {
  display: table-cell;
  border-bottom: 1px solid #eee;
}
.ios-alert {
  /* position: absolute;
        top: -44px;
        right: -404px; */
  color: orange;
  font-size: 16px;
  cursor: pointer;
}
.too {
  position: absolute;
  left: 113px;
  top: -1px;
}
.my-upload {
  margin-bottom: -6px !important;
}
</style>
